// 用户状态管理切片
// 使用Redux Toolkit创建用户相关的状态管理逻辑
import {createSlice, PayloadAction} from "@reduxjs/toolkit"
import type {IUserInfoResponse} from "../../types/data"

// 用户状态接口定义
export interface UserState {
  token: string // 用户认证token，用于身份验证
  isNew: boolean // 标识用户是否为新注册用户
  userInfo: IUserInfoResponse | null // 用户详细信息对象
}

// 创建用户状态切片
// name: 切片名称，用于在Redux store中标识该切片
export const userSlice = createSlice({
  name: "user",
  initialState: {
    token: "",
    isNew: false,
    userInfo: null,
  } as UserState,
  reducers: {
    // Sets the authentication token
    setToken: (state, action: PayloadAction<string>) => {
      state.token = action.payload
    },
    // Sets whether user is newly registered
    setIsNew: (state, action: PayloadAction<boolean>) => {
      state.isNew = action.payload
    },
    // Sets detailed user information
    setUserInfo: (state, action: PayloadAction<IUserInfoResponse>) => {
      state.userInfo = action.payload
    },
    // Clears the authentication token (logout)
    clearToken: state => {
      state.token = ""
    },
  },
})

// 导出所有action creators
// 这些方法用于dispatch操作来更新用户状态
export const {setToken, setIsNew, setUserInfo, clearToken} = userSlice.actions
// Returns the current authentication token
// 选择器函数：获取当前用户token
// @returns 当前用户的认证token
export const selectCurrentToken = (state: {user: UserState}) => state.user.token

// Returns whether user is newly registered
// 选择器函数：获取用户是否为新注册状态
// @returns boolean值表示用户是否为新注册
export const selectIsNew = (state: {user: UserState}) => state.user.isNew

// Returns detailed user information
// 选择器函数：获取用户详细信息
// @returns 用户详细信息对象或null
export const selectUserInfo = (state: {user: UserState}) => state.user.userInfo

export default userSlice.reducer
